export function timeFix () {
  const time = new Date()
  const hour = time.getHours()
  return hour < 9 ? '早上好' : hour <= 11 ? '上午好' : hour <= 13 ? '中午好' : hour < 20 ? '下午好' : '晚上好'
}

export function welcome () {
  const arr = ['休息一会儿吧', '准备吃什么呢?', '要不要打一把 DOTA', '我猜你可能累了']
  const index = Math.floor(Math.random() * arr.length)
  return arr[index]
}

/**
 * 触发 window.resize
 */
export function triggerWindowResizeEvent () {
  const event = document.createEvent('HTMLEvents')
  event.initEvent('resize', true, true)
  event.eventType = 'message'
  window.dispatchEvent(event)
}

export function handleScrollHeader (callback) {
  let timer = 0

  let beforeScrollTop = window.pageYOffset
  callback = callback || function () {}
  window.addEventListener(
    'scroll',
    event => {
      clearTimeout(timer)
      timer = setTimeout(() => {
        let direction = 'up'
        const afterScrollTop = window.pageYOffset
        const delta = afterScrollTop - beforeScrollTop
        if (delta === 0) {
          return false
        }
        direction = delta > 0 ? 'down' : 'up'
        callback(direction)
        beforeScrollTop = afterScrollTop
      }, 50)
    },
    false
  )
}

/**
 * Remove loading animate
 * @param id parent element id or class
 * @param timeout
 */
export function removeLoadingAnimate (id = '', timeout = 1500) {
  if (id === '') {
    return
  }
  setTimeout(() => {
    document.body.removeChild(document.getElementById(id))
  }, timeout)
}
export function formatTime (time, option) {
  if (!time) {
    return
  }
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
            1 +
            '月' +
            d.getDate() +
            '日' +
            d.getHours() +
            '时' +
            d.getMinutes() +
            '分'
    )
  }
}
export function parseTime (time, cFormat) {
  if (!time) return
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const timeStr = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    // eslint-disable-next-line standard/computed-property-even-spacing
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return timeStr
}
/** 时间间隔日期计算 */
export function timesDate (star, end) {
  const starFilter = timeFilter.strToDate(star)
  const endFilter = timeFilter.strToDate(end)
  let starTime = new Date(starFilter)
  starTime.setHours(12)
  starTime.setMinutes(0)
  starTime.setSeconds(0)
  starTime = starTime.getTime()
  let endTime = new Date(endFilter)
  endTime.setHours(12)
  endTime.setMinutes(0)
  endTime.setSeconds(0)
  endTime = endTime.getTime()
  const a = parseInt(endTime) - parseInt(starTime)
  const c = 24 * 60 * 60 * 1000
  const b = parseInt(a / c)
  return b
  // const b = (a / c).toFixed(2)
  // const str = String(b)
  // const lastStr = parseInt(str.charAt(str.length - 1))
  // const lastButOne = parseInt(str.charAt(str.length - 2))
  // if (lastButOne >= 1) {
  //   return Math.ceil(b)
  // } else {
  //   if (lastStr >= 4) {
  //     return Math.ceil(b)
  //   } else {
  //     return Math.floor(b)
  //   }
  // }
}
/**
 * 重复验证（入住人员数据重复验证）
 * @param Array data  数据源
 * @param String currentVal 当前项值
 * @param String input的name 判断第几项 如：xxxx[1]xxx
 * @param Number type=1(入住信息) data:数据源格式[{xxx:xxx}]; type=2(房号) data:数据源格式[1,2,3]
 * @param String compare 比较项字段
 */
export function verifyRepeat (data, currentVal, name, type, compare) {
  let initStart = name.indexOf('[')
  let end = name.indexOf(']')
  initStart = initStart + 1
  end = end - 1
  const count = end - initStart
  let numChar = ''
  for (let i = 0; i <= count; i++) {
    numChar = numChar + name.charAt(initStart + i)
  }
  numChar = parseInt(numChar.replace(/(^\s*)|(\s*$)/g, ''))
  for (let i = 0; i < data.length; i++) {
    if (i !== numChar) {
      if (type === 1) {
        if (data[i] && data[i][compare] === currentVal) {
          return true
        }
      } else if (type === 2) {
        if (data[i] && data[i] === currentVal) {
          return true
        }
      }
    }
  }
}

const timeFilter = {
  isNull: function (fData, replaceData) {
    return this.isEmpty(fData) ? replaceData : fData
  },
  isEmpty: function (fData) {
    if (typeof fData === 'function') {
      return false
    }
    return typeof fData === 'undefined' || fData === undefined || fData === null ||
                 fData.length === 0 || fData === 'null' || (fData !== false && fData === '')
  },
  strToDate: function (str) {
    if (this.isEmpty(str)) {
      return null
    }
    const converted = Date.parse(str)
    let myDate = new Date(converted)
    if (isNaN(myDate)) {
      if (str.indexOf(':') !== -1) {
        str = str.replace(' ', '-')
        str = str.replace(':', '-')
        str = str.replace(':', '-') // 第二个时间
        const arys = str.split('-')
        myDate = new Date(arys[0], --arys[1], arys[2], this.isNull(arys[3], 0),
          this.isNull(arys[4], 0), this.isNull(arys[5], 0))
      } else {
        const arys = str.split('-')
        myDate = new Date(arys[0], --arys[1], arys[2])
      }
    }
    return myDate
  }
}

/**
 * 压缩图片
 * @param {*} img 图片
 * @param {*} Orientation 方向
 */
export const compress = (img, Orientation) => {
  console.log('Orientation:', Orientation)
  const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d')

  let width = img.width
  let height = img.height
  // 如果图片大于四百万像素，计算压缩比并将大小压至100万以下
  let ratio
  const maxWidth = 750

  const ww = maxWidth / width
  const hh = maxWidth / height
  // eslint-disable-next-line prefer-const
  ratio = (ww < hh) ? ww : hh
  if (ratio <= 1) {
    width = width * ratio
    height = height * ratio
  }

  canvas.width = width
  canvas.height = height

  // 清除画布
  ctx.clearRect(0, 0, width, height)
  // 图片展示并旋转
  // eslint-disable-next-line eqeqeq
  if (Orientation && Orientation != 1) {
    switch (Orientation) {
      case 6:
        // 旋转90度
        canvas.width = height
        canvas.height = width
        ctx.rotate(Math.PI / 2)
        // (0,-imgHeight) 从旋转原理图那里获得的起始点
        ctx.drawImage(img, 0, -height, width, height)
        break
      case 3:
        // 旋转180度
        ctx.rotate(Math.PI)
        ctx.drawImage(img, -width, -height, width, height)
        break
      case 8:
        // 旋转-90度
        canvas.width = height
        canvas.height = width
        ctx.rotate(3 * Math.PI / 2)
        ctx.drawImage(img, -width, 0, width, height)
        break
    }
  } else {
    ctx.drawImage(img, 0, 0, width, height)
  }
  // 进行最小压缩
  let ndata
  let qulaty = 1
  ndata = canvas.toDataURL('image/jpeg', qulaty)
  while (ndata.length > 520000) {
    qulaty = qulaty - 0.1
    ndata = canvas.toDataURL('image/jpeg', qulaty)
  }
  canvas.width = canvas.height = 0
  console.log(ndata)
  return ndata
}
